<template>
	<view>
		<view class="container">
			<view class="location-card">
				<view class="location-title">
					当前位置
					<u-icon name="reload" color="#2979ff" size="45" style="float: right" @click="refreshData"></u-icon>
				</view>
				<view class="location">{{weatherInfo.address}}</view>
			</view>

			<view class="weather-card">
				<view class="temperature">{{weatherInfo.temp || 0}}°C</view>
				<view class="FeelsLike">
					<view style="display: flex;">
						<i :class="['qi-' + weatherInfo.icon, 'forecast-icon']" style="font-size: 30px;
					height: 30px;
					line-height: 30px;
					color: #fde047;
					width: 30%;text-align: right;"></i>
						<view style="margin-left: 5px;height: 30px;line-height: 30px;">体感温度
							{{weatherInfo.feelsLike || 0}}°C
							<text style="color: #d0c1d2;">({{weatherInfo.text || '---'}})</text>
						</view>
					</view>

				</view>

			</view>


			<view style="width: 100%;height: 100%;">
				<MyButton type="tarea" :chartData="chartData" background="none" />
			</view>

			<view class="meta-data-card">
				<view style="color: #fff;font-size: 20px;">气象数据</view>
				<view class="card-container">
					<!-- 第一行 -->
					<view class="card-row">
						<view class="card-item">
							<view class="meta-label">
								<u-icon name="star-fill" color="#eab308" size="35"></u-icon>
								<text style="margin-left: 2px;">
									湿度
								</text>
							</view>
							<text class="meta-value">{{weatherInfo.humidity || 0}}%</text>
						</view>
						<view class="card-item">
							<view class="meta-label">
								<u-icon name="map" color="#facc15" size="35"></u-icon>
								<text style="margin-left: 2px;">
									风速
								</text>
							</view>
							<text class="meta-value">{{weatherInfo.windSpeed || 0}}km/h</text>
						</view>
					</view>

					<!-- 第二行 -->
					<view class="card-row">
						<view class="card-item">
							<view class="meta-label">
								<u-icon name="tags" color="#ef4444" size="35"></u-icon>
								<text style="margin-left: 2px;">
									气压
								</text>
							</view>
							<text class="meta-value">{{weatherInfo.pressure || 0}} hPa</text>
						</view>
						<view class="card-item">
							<view class="meta-label">
								<u-icon name="integral" color="#6366f1" size="35"></u-icon>
								<text style="margin-left: 2px;">
									风速
								</text>
							</view>
							<text class="meta-value">{{weatherInfo.windSpeed || 0}}km/h</text>
						</view>
					</view>
					<!-- 第三行 -->
					<view class="card-row">
						<view class="card-item">
							<view class="meta-label">
								<u-icon name="eye" color="#3c9cff" size="40"></u-icon>
								<text style="margin-left: 2px;">
									能见度
								</text>
							</view>
							<text class="meta-value">{{weatherInfo.vis || 0}} 公里</text>
						</view>
						<view class="card-item">
							<view class="meta-label">
								<u-icon name="pushpin-fill" color="#8b5cf6" size="35"></u-icon>
								<text style="margin-left: 2px;">
									近1h降水量
								</text>
							</view>
							<text class="meta-value">{{weatherInfo.precip || 0}}毫米</text>
						</view>
					</view>

				</view>

			</view>

			<view class="health-advice-card">
				<view class="advice-title">健康建议</view>
				<view class="advice-text">
					{{weatherInfo.healthAdvice}}
				</view>
			</view>

		</view>
		<!-- 推送滑动按钮 -->
		<view class="push-slide-wrapper">
			<view class="slide-track" @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd">

				<!-- 进度背景遮罩 -->
				<view class="slide-progress" :style="{ width: sliderX + 'px' }"></view>

				<!-- 中间文本和图标 -->
				<view class="slide-content">
					<u-icon name="send" color="#fff" size="28" />
					<text class="slide-text">{{ slideText }}</text>
				</view>

				<!-- 滑块 -->
				<view class="slider-handle" :style="{ transform: `translateX(${sliderX}px)` }">
					<u-icon name="arrow-right-double" size="40" color="#2979ff" />
				</view>
			</view>
		</view>


	</view>

</template>

<script>
	import {
		getDetailsData,
		sendMessageTuiSong
	} from '@/api/api'
	import WebSocketService from '@/utils/websocket.js'
	import MyButton from '@/components/temperatureChart.vue'

	export default {
		components: {
			MyButton
		},
		data() {
			return {
				sliderX: 0,
				startX: 0,
				isSliding: false,
				isLocked: false,
				slideText: '滑动一键推送你的关心 →',
				slideWidth: 0, // 轨道宽度
				chartData: {},
				weatherInfo: {},
				userInfo: {},
				longitudeInfo: {} //用户所在位置信息
			}
		},
		onLoad(options) {
			// this.getServerData();
		},
		async mounted() {

			/* 获取用户信息 */
			await this.getUserInfo()
			console.log('store:', this.$store);
			try {
				const locations = await this.$store.dispatch('location/initLocation');
				this.longitudeInfo = {
					latitude: parseFloat(locations.latitude.toFixed(2)),
					longitude: parseFloat(locations.longitude.toFixed(2))
				}

				console.log('用户地址信息：')
				console.log(this.longitudeInfo)
			} catch (e) {
				console.log(e)
				uni.showToast({
					title: '请先授权定位',
					icon: 'none',
					duration: 2000 // 显示 2 秒
				});
			}

			/** 获取页面数据 */
			await this.getData();

			// 获取滑动轨道宽度
			this.$nextTick(() => {
				const query = uni.createSelectorQuery().in(this);
				query.select('.slide-track').boundingClientRect(data => {
					this.slideWidth = data.width;
				}).exec();
			});
		},
		methods: {
			initWebSocketListener() {
				WebSocketService.onMessage((msg) => {
					if (msg.cmd === 11004) {
						console.log("处理指令：【11004】")
						this.handleMessageList(msg)
					}
				})
			},
			/**
			 * 刷新地址信息
			 */
			async refreshData() {
				try {
					const locations = await this.$store.dispatch('location/initLocation');
					this.longitudeInfo = {
						latitude: parseFloat(locations.latitude.toFixed(2)),
						longitude: parseFloat(locations.longitude.toFixed(2))
					}
					console.log("重新获取地址信息: ")
					console.log(this.longitudeInfo)
				} catch (e) {
					console.log(e)
					uni.showToast({
						title: '请先授权定位',
						icon: 'none',
						duration: 2000 // 显示 2 秒
					});
				}

				this.getData()

			},
			/** 获取用户信息 */
			getUserInfo() {
				const that = this
				uni.getStorage({
					key: 'userInfo',
					success: (res) => {
						if (res && res.data) {
							that.userInfo = res.data
						} else {
							uni.showToast({
								title: '用户未登录，请登录后重试！',
								icon: 'none',
								duration: 1000 // 显示 2 秒
							});

							setTimeout(() => {
								uni.switchTab({
									url: '/pages/userInfo/userInfo'
								});
							}, 800); // 等待时间 = Toast显示时间
						}
					},
					fail: (err) => {
						uni.showToast({
							title: '用户未登录，请登录后重试！',
							icon: 'none',
							duration: 1000 // 显示 2 秒
						});

						setTimeout(() => {
							uni.switchTab({
								url: '/pages/userInfo/userInfo'
							});
						}, 800); // 等待时间 = Toast显示时间
					}
				})

			},
			onTouchStart(e) {
				if (this.isLocked) return;
				this.startX = e.touches[0].clientX;
				this.isSliding = true;
				this.slideText = '滑动中...';
			},
			onTouchMove(e) {
				if (!this.isSliding || this.isLocked) return;
				const moveX = e.touches[0].clientX;
				let distance = moveX - this.startX;

				const maxDistance = this.slideWidth - 80; // 保证滑块不超出

				if (distance < 0) distance = 0;
				if (distance > maxDistance) distance = maxDistance;

				this.sliderX = distance;
			},
			onTouchEnd() {
				if (this.isLocked) return;
				const percent = this.sliderX / (this.slideWidth - 80);

				if (percent >= 0.9) {
					this.triggerPush();
				} else {
					this.sliderX = 0;
					this.slideText = '滑动一键推送你的关心 →';
					this.isSliding = false;
				}
			},
			async triggerPush() {
				/**消息推送*/
				// let param = {
				// 	userId: this.userInfo.userId,
				// 	content: '今天有雨，出门记得带伞，别淋湿啦~ 需要接你下班的话，随时喊我！ 💦',
				// 	acceptId: '-1',
				// 	messageType: '天气提醒'
				// }

				// await sendMessageTuiSong(param).then(res => {

				// 	if (res.code === 200) {
				// 		this.slideText = '推送成功 🎉';
				// 		uni.showToast({
				// 			title: '推送成功',
				// 			icon: 'success',
				// 			duration: 2000 // 显示 2 秒
				// 		});

				// 	} else {
				// 		this.slideText = '推送失败 🎉';
				// 		uni.showToast({
				// 			title: '推送失败',
				// 			icon: 'error',
				// 			duration: 2000 // 显示 2 秒
				// 		});
				// 	}

				// })

				WebSocketService.send({
					"CMD": "1006",
					"ext": {
						"userId": this.userInfo.userId,
						"acceptId": '-1',
						"messageType": "系统通知",
						"content": "今天有雨，出门记得带伞，别淋湿啦~ 需要接你下班的话，随时喊我！ 💦",
						"title": "天气提醒"
					}
				})


				this.slideText = '推送成功 🎉';
				uni.showToast({
					title: '推送成功',
					icon: 'success',
					duration: 2000 // 显示 2 秒
				});


				this.isLocked = true;
				this.sliderX = this.slideWidth - 80;

				uni.showToast({
					title: '推送成功',
					icon: 'success',
					duration: 2000 // 显示 2 秒
				});

				// 重置状态
				setTimeout(() => {
					this.sliderX = 0;
					this.slideText = '滑动一键推送你的关心 →';
					this.isSliding = false;
					this.isLocked = false;
				}, 1500);
			},
			/**
			 * 获取天气详细数据
			 */
			getData() {
				const that = this
				let param = {
					...that.longitudeInfo
				}
				getDetailsData(param).then(res => {
					if (res.code && res.data) {
						let list = res.data.sixHourWeatherTrend

						this.chartData = this.processWeatherData(list)

						this.weatherInfo = res.data
					}
				})

			},
			/**
			 * 处理24小时趋势数据
			 */
			processWeatherData(data) {
				/* 跳转到首页*/
				// 1. 获取实际数据（最多取前6个）
				const actualData = data.slice(0, 6);

				// 2. 计算需要补充的数据点数量
				const remainingCount = 6 - actualData.length;

				// 3. 生成补充数据（时间推算，温度=0）
				const supplementaryData = [];
				if (remainingCount > 0) {
					// 获取最后一个有效时间点
					const lastTime = actualData.length > 0 ?
						actualData[actualData.length - 1].fxTime :
						"00:00";

					// 解析最后时间的小时和分钟
					const [lastHour, lastMinute] = lastTime.split(':').map(Number);

					// 生成补充时间点（每小时递增）
					for (let i = 1; i <= remainingCount; i++) {
						const nextHour = (lastHour + i) % 24;
						const formattedHour = String(nextHour).padStart(2, '0');
						supplementaryData.push({
							fxTime: `${formattedHour}:${lastMinute.toString().padStart(2, '0')}`,
							temp: "0"
						});
					}
				}

				// 4. 合并实际数据和补充数据
				const combinedData = [...actualData, ...supplementaryData];

				// 5. 返回图表数据结构
				return {
					categories: combinedData.map(item => item.fxTime),
					series: [{
						name: '趋势',
						data: combinedData.map(item => Number(item.temp)),
						color: '#3c9cff',
						area: true
					}]
				};
			},
			toIndex() {
				uni.switchTab({
					url: '/pages/index/index'
				});
			},
			// getServerData() {
			// 	setTimeout(() => {
			// 		this.chartData = {
			// 			categories: [
			// 				'08:00', '09:00', '10:00',
			// 				'11:00', '12:00', '13:00',
			// 				'14:00'
			// 			],
			// 			series: [{
			// 				name: '趋势',
			// 				data: [21, 25, 24, 26, 22, 24, 25],
			// 				color: '#3c9cff',
			// 				area: true // 开启区域渐变填充
			// 			}]
			// 		};
			// 	}, 300);
			// }
		}
	}
</script>

<style scoped>
	.container {
		padding: 20px;
		background-color: #5398e2;
	}

	.location-card {
		background-color: #65abe6;
		padding: 20px;
		border-radius: 10px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		margin-bottom: 20px;
	}

	.meta-data-card {
		background-color: #65abe6;
		padding: 20px;
		border-radius: 10px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		margin-bottom: 20px;
		margin-top: 20px;
	}

	.location-title {
		font-size: 23px;
		font-weight: bold;
		margin-bottom: 10px;
		color: #fff;
	}

	.location {
		font-size: 16px;
		color: #fff;
		opacity: 0.6;
	}

	.weather-card {
		padding: 20px;
		border-radius: 10px;
		margin-bottom: 20px;
		text-align: center;
	}

	.temperature {
		font-size: 60px;
		font-weight: bold;
		color: #fff;
	}

	.FeelsLike {
		font-size: 18px;
		color: #fff;
	}

	.card-container {
		padding: 16rpx;
		margin-top: 10px;
	}

	.card-row {
		display: flex;
		justify-content: space-between;
		margin-bottom: 20rpx;
		/* 行间距 */
	}

	.card-item {
		width: 45%;
		/* 留出2%的间隙 */
		background: #65abe6;
		border-radius: 12rpx;
		padding: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);

		/* 卡片动画效果（可选） */
		transition: all 0.3s ease;
		opacity: 0.8;
	}

	.card-item:active {
		transform: scale(0.98);
		/* 点击效果 */
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.12);
	}

	.meta-label {
		display: block;
		font-size: 30rpx;
		color: #fff;
		margin-bottom: 8rpx;
		text-align: center;
	}

	.meta-value {
		display: block;
		font-size: 35rpx;
		font-weight: bold;
		color: #fff;
		text-align: center;
	}

	.health-advice-card {
		background-color: #65abe6;
		padding: 20px;
		border-radius: 10px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		margin-bottom: 20px;
	}

	.advice-title {
		font-size: 23px;
		color: #fff;
	}

	.advice-text {
		background-color: #65abe6;
		padding: 20px;
		border-radius: 10px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		margin-bottom: 20px;
		margin-top: 10px;
		color: #fff;
		font-size: 18px;
		opacity: 0.8;
	}

	/* 浮动滑动按钮 */
	.push-slide-wrapper {
		position: fixed;
		bottom: 50rpx;
		left: 50%;
		transform: translateX(-50%);
		width: 90%;
		z-index: 999;
	}

	.slide-track {
		width: 100%;
		height: 100rpx;
		border-radius: 50rpx;
		background: linear-gradient(to right, #a0cfff, #409eff);
		overflow: hidden;
		position: relative;
		box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.2);
		will-change: transform;
		transform: translateZ(0);
		backface-visibility: hidden;
	}

	.slide-progress {
		position: absolute;
		top: 0;
		left: 0;
		height: 100%;
		background: linear-gradient(to right, #2979ff, #1e88e5);
		border-radius: 50rpx;
		transition: width 0.1s ease;
		z-index: 0;
	}

	.slide-content {
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #fff;
		font-weight: bold;
		font-size: 30rpx;
		position: relative;
		z-index: 1;
		pointer-events: none;
	}

	.slide-text {
		margin-left: 12rpx;
	}

	.slider-handle {
		position: absolute;
		top: 10rpx;
		left: 0;
		width: 80rpx;
		height: 80rpx;
		background-color: #fff;
		border-radius: 50%;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 2;
		transition: transform 0.1s ease;
		will-change: transform;
		transform: translateZ(0);
		backface-visibility: hidden;
	}
</style>